package com.gitee.zeric.codec.generaters;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.gitee.zeric.codec.exception.ParamErrorException;
import com.gitee.zeric.codec.util.VUtils;

/**
 * @author zj
 * @date 2021/12/20
 */
public abstract class AbstractCodeGerator implements CodeGenerater {


    /**
     * 生成编码
     *
     * @param ruleCode
     * @param jsonObject
     * @return java.lang.String
     * @author zj
     * @date 2021/12/20 14:54
     */
    public String generateCode(String ruleCode, JSONObject jsonObject) {
        //校验规则参数
        this.checkParam(jsonObject);
        //生成编码
        return this.generate(ruleCode, jsonObject);
    }

    @Override
    public void checkParam(JSONObject paramJson) {
        VUtils.isTure(paramJson == null).throwMessage("编码规则参数不能为空！");
        for (String field : fields()) {
            VUtils.isTure(!paramJson.containsKey(field) || paramJson.get(field) == null).throwMessage("编码规则参数缺失属性！field=" + field);
            //size
            if (StrUtil.equals("size", field)) {
                Integer size = paramJson.getInteger(field);
                VUtils.isTure(size > 20 || size < 0).throwMessage("编码规则size不能超过20或小于0！size=" + size);
            }
        }
    }

    @Override
    public int size(JSONObject paramJson) {
        if(paramJson!=null && paramJson.containsKey("size")){
            return paramJson.getInteger("size");
        }
        return 0;
    }

    /**
     * 需要校验的字段
     */
    protected abstract String[] fields();
}
